﻿using AuthCenter_HuangJingtao.Infrastructure.Implements;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Infrastructure;
using Microsoft.EntityFrameworkCore;
using System.Reflection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace AuthCenter_HuangJingtao.Read.Api.Extensions
{
    public static class ServiceCollectionExtensions
    {

        /// 注册sqlserver数据库
        //public static IServiceCollection AddDbcontextServe<TDbContext>(this IServiceCollection Services, string? connectionString,bool enablesqllog) where TDbContext : DbContext
        //{
        //    return Services.AddDbContext<TDbContext>(builder => 
        //    {
        //        builder.UseSqlServer(connectionString, action =>
        //        {
        //            action.EnableRetryOnFailure(
        //                maxRetryCount: 10,
        //                maxRetryDelay: TimeSpan.FromSeconds(60),
        //                errorNumbersToAdd: null
        //                );
        //        }).EnableSensitiveDataLogging();
        //        if (enablesqllog)
        //        {
        //            builder.UseLoggerFactory(LoggerFactory.Create(configure: configure  =>
        //            {
        //                configure
        //                   .AddFilter((category,level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
        //                   .AddConsole();
        //            }));
        //        }
        //    });
        //}
        /// 注册Mysql数据库
        public static IServiceCollection AddDbContextService<TDbContext>(this IServiceCollection services, string? connectionString, bool enableSqlLog)
    where TDbContext : DbContext
        {
            return services.AddDbContext<TDbContext>(builder =>
            {
                // 使用MySQL提供程序,自动识别版本
                builder.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), options =>
                {
                    options.EnableRetryOnFailure(
                        maxRetryCount: 10,
                        maxRetryDelay: TimeSpan.FromSeconds(60),
                        errorNumbersToAdd: null
                    );
                }).EnableSensitiveDataLogging();

                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                            .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                            .AddConsole();
                    }));
                }
            });
        }

        //注册jwt加密验证

        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
               .AddJwtBearer(options =>
               {

                   //取出私钥
                   var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                   options.TokenValidationParameters = new TokenValidationParameters()
                   {
                       //验证发布者
                       ValidateIssuer = true,
                       ValidIssuer = builder.Configuration["Authentication:Issuer"],
                       //验证接收者
                       ValidateAudience = true,
                       ValidAudience = builder.Configuration["Authentication:Audience"],
                       //验证是否过期
                       ValidateLifetime = true,
                       //验证私钥
                       IssuerSigningKey = new SymmetricSecurityKey(secretByte),

                   };
               });
        }



        //依赖扩展类
        public static IServiceCollection AddServices(this IServiceCollection Services)
        {
            Services.AddScoped(typeof(IBaseReponsitory<>), typeof(BaseReponsitory<>));
            Services.AddMediatR(c => c.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

            return Services;
        }
    }
}
